/**
 * 
 */
package com.aspire.android.heliar.pub.analyzer;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.util.Log;

import com.aspire.android.heliar.Heliar;
import com.aspire.android.heliar.pub.analyzer.mms.StandardMMSAnalyzer;
import com.aspire.android.heliar.utils.Configuration;

/**
 * @author panglei
 * 
 */
public class PubAnalyzerManager {

	private PubAnalyzer defaultPubAnalyzer = new StandardMMSAnalyzer();
	private Map<String, PubAnalyzer> analyzers = new HashMap<String, PubAnalyzer>();
	private Map<String, List<String>> router = new HashMap<String, List<String>>();

	/**
	 * 获取指定的Pub解析器
	 * 
	 * @param name
	 *            解析器名字
	 * @return 若指定名字不存在，则返回defaultPubAnalyzer
	 */
	public PubAnalyzer getPubAnalyzer(String name) {

		Set<String> analyzerNames = router.keySet();
		for (String analyzerName : analyzerNames) {
			List<String> mmsTitles = router.get(analyzerName);
			for (String mmsTitle : mmsTitles) {
				if (name.contains(mmsTitle)) {
					return analyzers.get(analyzerName);
				}
			}
		}
		return defaultPubAnalyzer;
	}

	/**
	 * 重新加载解析器
	 */
	public void reloadAnalyzer() {
		analyzers.put(StandardMMSAnalyzer.ANALYZER_NAME, defaultPubAnalyzer);
		try {
			loadConfig();
		} catch (UnsupportedEncodingException e) {
			Log.e(Heliar.LOG_TAG, e.getMessage(), e);
		}
	}

	private void loadConfig() throws UnsupportedEncodingException {
		Set<String> analyzerNames = analyzers.keySet();
		for (String analyzerName : analyzerNames) {
			String config = new String(Configuration.getInstance()
					.getConfiguration(analyzerName).getBytes("iso-8859-1"),
					"UTF-8");
			String[] mmsTitles = config.split(",");
			if (mmsTitles.length > 0) {
				router.put(analyzerName, new ArrayList<String>());
			}
			for (String mmsTitle : mmsTitles) {
				router.get(analyzerName).add(mmsTitle);
			}
		}
	}

	private static PubAnalyzerManager instance = new PubAnalyzerManager();

	private PubAnalyzerManager() {
		// init Analyzer
		reloadAnalyzer();
	}

	public static PubAnalyzerManager getInstance() {
		return instance;
	}
}
